document.addEventListener('DOMContentLoaded',
  function() {
    var canvas = document.getElementById('signature-pad');
    var ctx = canvas.getContext('2d'); // 获取该画布的 2D 渲染上下文，它包含了绘制图形所需的各种方法和属性
    var drawing = false;
    var strokeStyle = 'pen';
    var signatureData = null;

    var signaturePad = new SignaturePad(canvas);
    // undoStack栈 和 redoStack栈，分别用来追踪撤销和重做的历史状态
    var undoStack = [];
    var redoStack = [];

    function resizeCanvas() {
      if (signatureData) {
        var img = new Image();
        img.src = signatureData;
        img.onload = function() {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          canvas.width = canvas.offsetWidth;
          canvas.height = canvas.offsetHeight;
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        };
      } else {
        canvas.width = canvas.offsetWidth;
        canvas.height = canvas.offsetHeight;
      }

      // 设置初始笔画样式
      ctx.lineWidth = strokeStyle === 'pen' ? 2 : 5;
      ctx.lineCap = 'round';

      signaturePad.clear(); // 否则 isEmpty() 可能会返回错误值
      if (undoStack.length > 0) {
        signaturePad.fromData(undoStack[undoStack.length - 1]);
      }
    }

    function startDrawing(e) {
      drawing = true;
      ctx.beginPath(); // 开启新的绘图路径
      // 将画笔定位到鼠标点击的准确位置
      ctx.moveTo(e.offsetX || e.touches[0].clientX - canvas.offsetLeft, e.offsetY || e.touches[0].clientY - canvas.offsetTop);
    }

    function draw(e) {
      if (drawing) {
        // 绘制一条直线到新位置
        ctx.lineTo(e.offsetX || e.touches[0].clientX - canvas.offsetLeft, e.offsetY || e.touches[0].clientY - canvas.offsetTop);
        ctx.stroke(); // 将这条线实际画到画布上
      }
    }

    function stopDrawing() {
      drawing = false;
      signatureData = canvas.toDataURL(); // 将画布内容转换为图像数据保存，避免调整画布大小时内容消失
    }

    function exportCanvas(format) {
      var exportCanvas = document.createElement('canvas');
      if(isEmptyCanvas(exportCanvas)) {
        alert('请先签名！');
        return;
      }
      exportCanvas.width = canvas.width;
      exportCanvas.height = canvas.height;
      var exportCtx = exportCanvas.getContext('2d');
  
      // 用白色填充背景
      exportCtx.fillStyle = '#fff';
      exportCtx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
  
      // 绘制签名
      exportCtx.drawImage(canvas, 0, 0);
  
      // 导出画布
      var dataURL = exportCanvas.toDataURL(`image / ${format}`);
      var link = document.createElement('a');
      link.href = dataURL;
      link.download = `signature.${format}`;
      link.click();
    }

    function isEmptyCanvas(canvas) {
      var blank = document.createElement('canvas');
      blank.width = canvas.width;
      blank.height = canvas.height;
      return canvas.toDataURL() === blank.toDataURL(); // 比较值相等则为空
    }

    // 将签名板的当前状态存储到撤销栈中
    function saveState() {
      undoStack.push(deepCopy(signaturePad.toData()));
      redoStack = [];
    }

    function undo() {
      if (undoStack.length > 0) {
        redoStack.push(deepCopy(signaturePad.toData()));
        undoStack.pop();
        signaturePad.clear();
        if (undoStack.length) {
          var lastStroke = undoStack[undoStack.length - 1];
          signaturePad.fromData(lastStroke, {
            clear: false
          });
        }
      }
    }

    function redo() {
      if (redoStack.length > 0) {
        undoStack.push(deepCopy(signaturePad.toData()));
        var nextState = redoStack.pop();
        signaturePad.clear();
        if (nextState.length) {
          signaturePad.fromData(nextState);
        }
      }
    }

    function deepCopy(data) {
      return JSON.parse(JSON.stringify(data));
    }

    // 鼠标事件
    canvas.addEventListener('mousedown', startDrawing); // 触发绘图动作
    canvas.addEventListener('mousemove', draw); // 根据鼠标的当前位置绘制线条
    canvas.addEventListener('mouseup', stopDrawing); // 鼠标按钮释放
    canvas.addEventListener('mouseout', stopDrawing); // 鼠标光标移出画布

    // 触摸事件
    canvas.addEventListener('touchstart', startDrawing);
    canvas.addEventListener('touchmove', draw);
    canvas.addEventListener('touchend', stopDrawing);
    canvas.addEventListener('touchcancel', stopDrawing);

    // 撤销
    document.getElementById('undo').addEventListener('click', undo);

    // 重做
    document.getElementById('redo').addEventListener('click', redo);

    // 绘图结束时保存状态
    signaturePad.addEventListener("endStroke", () => {
      saveState();
    });

    // 清除按钮清除画布
    document.getElementById('clear').addEventListener('click',
    function() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      signatureData = null;
      signaturePad.clear();
      undoStack = [];
      redoStack = [];
    });


    // 选择笔刷
    document.getElementById('stroke-style').addEventListener('change',
    function(e) {
      strokeStyle = e.target.value;
      if (strokeStyle === 'pen') {
        ctx.lineWidth = 2;
        ctx.lineCap = 'round';
      } else if (strokeStyle === 'brush') {
        ctx.lineWidth = 5;
        ctx.lineCap = 'round';
      }
    });

    // 导出画布内容位 png 形式
    document.getElementById('export-png').addEventListener('click',
    function() {
      exportCanvas('png');
    });
  
    // 导出画布内容位 jpeg 形式
    document.getElementById('export-jpeg').addEventListener('click',
    function() {
      exportCanvas('jpeg');
    });

    // 初始画布设置
    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();
  });
  